package org.ucas.faker.web.utils.wx;

import org.springframework.stereotype.Component;
import org.ucas.faker.web.utils.mql.domain.Condition;
import org.ucas.faker.web.utils.mql.domain.Where;
import org.ucas.faker.web.utils.mql.exception.MqlParseException;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class WxTranslator {

  public String translate(String query) {
//    Query select = MqlParseVisitor.generate(query);
//    return visitWhere(select.getWhere());

    String res = query;
    res = res.replaceAll("\'","");
    res = res.replaceAll("\"","");
    return res;
  }


  public String visitWhere(Where where) {
    if(where instanceof Condition) return visitCond((Condition) where);

    List<String> children = where.getWheres().stream().map(this::visitWhere)
        .filter(q -> q != null && !"".equals(q.trim())).collect(Collectors.toList());
    if(children.size() == 0) return null;
    if(where.getConn() == Where.CONN.NOT) {
      return "( not " + children.get(0) + " )";
    } else {
      String seq = where.getConn() == Where.CONN.AND ? " and " : " or ";
      return "( " + children.stream().collect(Collectors.joining(seq)) +" )";
    }
  }

  public String visitCond(Condition cond) {
    if(cond.getOpear() == Condition.OPEAR.CONTAINS) {
      String name = cond.getName();
      if(name == null) throw new MqlParseException("Unsupported patent field : " + cond.getName()+"!");
      return name + " = " + cond.getValue().toString();
    }
    return null;
  }
}
